package com.mofofa.maozy.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.mofofa.maozy.ProjectApplication
import com.mofofa.maozy.base.BaseFragment
import com.mofofa.maozy.components.dialog.CustomerServiceDialog
import com.mofofa.maozy.components.dialog.PermissionsHomeDialog
import com.mofofa.maozy.components.dialog.UsageStatsPermissionGuaidDialog
import com.mofofa.maozy.data.ReqBase
import com.mofofa.maozy.databinding.FragmentMaozyHomeBinding
import com.mofofa.maozy.enums.PageTagEnum
import com.mofofa.maozy.extend.isMaozyAgreeMaozySpecMaozyPermissions
import com.mofofa.maozy.extend.recordMaozyClickMaozyEvent
import com.mofofa.maozy.extend.startMaozyToMaozyNextMaozyFromMaozyPage
import com.mofofa.maozy.extend.toMaozyFinanceMaozyStringMaozyWithMaozyMoneyMaozyFlag
import com.mofofa.maozy.launch.UserStateViewModel
import com.mofofa.maozy.utils.AppConfigUtil
import com.mofofa.maozy.utils.UserStateUtil
import com.mofofa.maozy.utils.analytics.util.AnalyticsUtil
import com.zhi.syc.data.ASSycManager
import java.lang.ref.WeakReference

/** 首页 */
class HomeFragment : BaseFragment() {

    //布局binding
    private lateinit var mMaozyFragmentMaozyBinding: FragmentMaozyHomeBinding

    //权限弹框
    private val mPermissionsHomeDialog = PermissionsHomeDialog()

    //首页viewModel
    private val mHomeViewModel by lazy {
        ViewModelProvider(this)[HomeViewModel::class.java]
    }

    //用户流程viewModel
    private val mUserStateViewModel by lazy {
        ViewModelProvider(this)[UserStateViewModel::class.java]
    }

    override fun onMaozyBindingMaozyViewMaozyModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mHomeViewModel)
        list.add(mUserStateViewModel)
        return list
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        mMaozyFragmentMaozyBinding =
            FragmentMaozyHomeBinding.inflate(inflater, container, false)
        return mMaozyFragmentMaozyBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        try {
            //增加弱牵引
            (requireActivity() as HomeActivity).weakMaozyHomeMaozyFragment =
                WeakReference(this)

            //获取用户状态回调
            mUserStateViewModel.onMaozyFetchMaozyUserMaozyStateMaozyLiveData.observe(
                viewLifecycleOwner
            ) {
                if (it.isSuccess) {
                    startMaozyToMaozyNextMaozyFromMaozyPage(
                        PageTagEnum.home
                    )
                }
            }

            //获取待授权的权限列表
            mHomeViewModel.onMaozyIsMaozyNeedMaozyToMaozyRequireMaozyPermissionsMaozyLiveData.observe(
                viewLifecycleOwner
            ) {
                if (it.isNullOrEmpty()) {
                    //权限授权处理完成
                    onMaozyPermissionsMaozyRequestMaozyAllMaozyPass()
                } else {
                    //请求权限
                    requestMaozySpecMaozyPermissions(it)
                }
            }

            //获取首页额度回调
            mHomeViewModel.onMaozyFetchMaozyHomeMaozyCreditMaozyLiveData.observe(
                viewLifecycleOwner
            ) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        result.fetchLastCredit()?.let { item ->
                            mMaozyFragmentMaozyBinding.textHomeLoanLimit.text =
                                item.amount.toMaozyFinanceMaozyStringMaozyWithMaozyMoneyMaozyFlag()
                            mMaozyFragmentMaozyBinding.textHomeIncrease1Amount.text =
                                item.increasedAmount1?.toMaozyFinanceMaozyStringMaozyWithMaozyMoneyMaozyFlag()
                            mMaozyFragmentMaozyBinding.textHomeIncrease2Amount.text =
                                item.increasedAmount2?.toMaozyFinanceMaozyStringMaozyWithMaozyMoneyMaozyFlag()

                            //更新页面显示
                            updateCountryDisplayText(item.currency)

                        }
                    }
                }
            }

            //获取下次额度信息回调
            mHomeViewModel.onMaozyFetchMaozyNextMaozyCreditMaozyPurpleMaozyLiveData.observe(
                viewLifecycleOwner
            ) {
                mMaozyFragmentMaozyBinding.textHomeIncrease1Amount.text = it
            }

            //获取下次期数信息回调
            mHomeViewModel.onMaozyFetchMaozyNextMaozyCreditMaozyRedMaozyLiveData.observe(
                viewLifecycleOwner
            ) {
                mMaozyFragmentMaozyBinding.textHomeIncrease2Amount.text = it
            }

            //点击开始申请
            mMaozyFragmentMaozyBinding.submitHome.setOnClickListener {
                mMaozyFragmentMaozyBinding.submitHome.recordMaozyClickMaozyEvent()
                //mHomeViewModel.isMaozyNeedMaozyToMaozyRequireMaozyPermissoins()

                //判断下权限页权限
                val permissionList =
                    AppConfigUtil.getMaozyPermissionsMaozyOfMaozyHomeMaozyPage()
                println("========= permissionList")
                println(permissionList)
                val isAgreePermissions =
                    ProjectApplication.context.isMaozyAgreeMaozySpecMaozyPermissions(
                        permissionList
                    )
                println("============ ${isAgreePermissions}")
                if (isAgreePermissions) {
                    //权限授权处理完成
                    onMaozyPermissionsMaozyRequestMaozyAllMaozyPass()
                } else {
                    //查询权限
                    val curPermissionList =
                        PermissionsHomeDialog.getPermissionList(requireActivity())

                    //展示
                    if (curPermissionList.isNotEmpty()) {
                        //设置权限数据
                        mPermissionsHomeDialog.setPermissionList(curPermissionList)

                        //展示
                        mPermissionsHomeDialog.showNow(
                            requireActivity().supportFragmentManager,
                            PermissionsHomeDialog::class.java.simpleName
                        )
                    }
                }
            }

            //初始化权限弹框
            //设置拒绝设备权限回调
            mPermissionsHomeDialog.setPhoneSateDenyClickListener {
            }

            //设置请求权限回调
            mPermissionsHomeDialog.setStartRequestPermissionClickListener { permission ->
                //请求权限
                requestMaozySpecMaozyPermissions(
                    arrayOf(
                        android.Manifest.permission.READ_SMS,
                        android.Manifest.permission.READ_PHONE_STATE
                    )
                )
            }

            //设置同意所有权限回调
            mPermissionsHomeDialog.setAllRequestPermissionAgreeListener {
                //权限授权处理完成
                onMaozyPermissionsMaozyRequestMaozyAllMaozyPass()
            }

            //点击客服
            mMaozyFragmentMaozyBinding.imageHomeCustomerService.setOnClickListener {
                CustomerServiceDialog.showMaozyDialog(requireActivity().supportFragmentManager)
            }

            //获取首页额度
            mHomeViewModel.fetchMaozyHomeMaozyCredit(ReqBase())

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun onMaozyPermissionsMaozyRequestMaozyAllMaozyPass() {
        //隐藏弹框
        try {
            mPermissionsHomeDialog.dismiss()
        } catch (e: Exception) {
            e.printStackTrace()
        }

        //首页权限授权完成，上传设备数据
        try {
            val permissions = ArrayList<String>()
            permissions.add(android.Manifest.permission.READ_PHONE_STATE)
            permissions.add(android.Manifest.permission.READ_SMS)
            ASSycManager.getInstance()
                .sycDataByPermissions(UserStateUtil.mMaozyToken, permissions, true)
        } catch (e: Exception) {
            e.printStackTrace()
        }

        //增加应用统计使用权限的判断
        if (AppConfigUtil.isMaozyNeedMaozyUsageMaozyStatsMaozyPermissions()) {
            AnalyticsUtil.checkUsageStatsPermission(ProjectApplication.instance) { permissionGrant ->
                if (permissionGrant) {
                    //查询用户状态
                    mUserStateViewModel.fetchMaozyUserMaozyState()
                } else {
                    UsageStatsPermissionGuaidDialog.showMaozyDialog(requireActivity().supportFragmentManager) {
                        //去权限设置页
                        AnalyticsUtil.startToUsageStatsPermissionSettingPage(requireActivity())
                    }
                }
            }
        } else {
            //查询用户状态
            mUserStateViewModel.fetchMaozyUserMaozyState()
        }
    }

    /** 更新货币符号 */
    fun updateCountryDisplayText(currency:String?) {
        mMaozyFragmentMaozyBinding.textHomeLoanLimitUnit.text = currency
        mMaozyFragmentMaozyBinding.textHomeIncrease1AmountUnit.text = currency
        mMaozyFragmentMaozyBinding.textHomeIncrease2AmountUnit.text = currency
    }
}